package com.ssfeng.youxia.dao.impl;

import com.ssfeng.youxia.shiro.SessionUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.apache.shiro.session.mgt.eis.SessionIdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

//@Repository("shiroSessionDao")
public class RedisShiroSessionDao extends CachingSessionDAO {

	private static final Logger logger = LoggerFactory.getLogger(RedisShiroSessionDao.class);

	@Autowired
    private StringRedisTemplate stringRedisTemplate;

	@Override
	protected void doUpdate(Session session) {
		String sessionStr = SessionUtils.base64EncodeSession(session);
		stringRedisTemplate.opsForValue().set("youxia:session:"+session.getId(),sessionStr,session.getTimeout(), TimeUnit.MILLISECONDS);
	}

	@Override
	protected void doDelete(Session session) {
        stringRedisTemplate.delete("youxia:session:" + session.getId());
	}

	@Override
	protected Serializable doCreate(Session session) {
		SessionIdGenerator generator = this.getSessionIdGenerator();
		Serializable id = this.getSessionIdGenerator().generateId(session);
		this.assignSessionId(session, id);
		String sessionStr = SessionUtils.base64EncodeSession(session);
		stringRedisTemplate.opsForValue().set("youxia:session:"+session.getId(),sessionStr,session.getTimeout(), TimeUnit.MILLISECONDS);
		return id;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
        String value = stringRedisTemplate.opsForValue().get("youxia:session:" + sessionId);
		if (value == null) {
			return null;
		}
		Session session = SessionUtils.base64DcodeSession(value);
		return session;
	}
}
